package cn.col.gszf.controller;

import cn.col.gszf.pojo.Channel;
import cn.col.gszf.pojo.UserVotes;
import cn.col.gszf.service.ChannelService;
import cn.col.gszf.service.RedisService;
import cn.col.gszf.service.UserVotesService;
import cn.col.gszf.util.IPUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author wanghong
 * @created 2024-06-18 23:37
 * @description 获取频道入口
 **/
@Slf4j
@Controller
@RequestMapping("/channel")
public class ChannelController {

    @Resource
    private ChannelService channelService;

    @Resource(name = "redis-service")
    private RedisService redisService;

    @Resource(name = "userVotesServiceImpl")
    private UserVotesService userVotesService;

    /**
     * @Description 根据id获取频道详细信息
     * @Param: channelId, VID, model, request, response
     * @return: String
     * @Author: wanghong
     * @Date: 2024/6/23
     */
    @Transactional
    @GetMapping("/{channelId}")
    public String getChannelById(@PathVariable Integer channelId,
                      @CookieValue(value = "VID", required = false) String VID,
                      Model model,
                      HttpServletRequest request,
                      HttpServletResponse response) {
        String ip = IPUtil.getIpAddress(request);
        Channel channel = channelService.getById(channelId,VID,model,ip,response);
        model.addAttribute("votes", channel);
        model.addAttribute("allVotingNums", redisService.get("channel_" + channelId));
        return "channel";
    }

    /**
     * @Description 获取所有频道
     * @Param: Model
     * @return: String
     * @Author: wanghong
     * @Date: 2024/6/23
     */
    @GetMapping("")
    public String getAll(Model model) {
        List<Channel> channels = channelService.selectAllChannelInfo();
        model.addAttribute("channels", channels);
        return "channels";
    }
}
